<template>
  <div class="app-container">
    <div class="config-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>考核配置管理</h2>
        <p>创建、编辑和管理考核任务配置</p>
      </div>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="showCreateDialog">
          <i class="el-icon-plus"></i>
          新建配置
        </el-button>
        <el-button type="success" @click="refreshData">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
        <el-button type="warning" @click="batchToggleSchedule">
          <i class="el-icon-switch-button"></i>
          批量启用/禁用
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="配置名称">
            <el-input v-model="searchForm.configName" placeholder="请输入配置名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.enabled" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="定时任务">
            <el-select v-model="searchForm.scheduleEnabled" placeholder="请选择定时任务状态" clearable>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchConfigs">
              <i class="el-icon-search"></i>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh-left"></i>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 配置列表 -->
      <div class="config-table">
        <el-table 
          :data="configList" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="configName" label="配置名称" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="configDescription" label="描述" width="250" show-overflow-tooltip></el-table-column>
          <el-table-column prop="targetClass" label="目标类" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="methodName" label="方法名" width="120"></el-table-column>
          <el-table-column prop="scheduleCron" label="Cron表达式" width="150"></el-table-column>
          <el-table-column prop="scheduleEnabled" label="定时任务" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.scheduleEnabled"
                :active-value="1"
                :inactive-value="0"
                @change="toggleSchedule(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.enabled === 1 ? 'success' : 'danger'">
                {{ scope.row.enabled === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastExecuteTime" label="最后执行时间" width="180">
            <template slot-scope="scope">
              {{ formatTime(scope.row.lastExecuteTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="nextExecuteTime" label="下次执行时间" width="180">
            <template slot-scope="scope">
              {{ formatTime(scope.row.nextExecuteTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template slot-scope="scope">
              <div class="action-buttons">
                <el-tooltip content="编辑" placement="top">
                  <el-button size="mini" type="warning" plain circle icon="el-icon-edit" @click="editConfig(scope.row)" />
                </el-tooltip>
                <el-tooltip content="立即执行" placement="top">
                  <el-button size="mini" type="success" plain circle icon="el-icon-caret-right" @click="executeNow(scope.row)" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button size="mini" type="danger" plain circle icon="el-icon-delete" @click="deleteConfig(scope.row)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </div>

      <!-- 创建/编辑配置对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="800px"
        @close="resetForm"
      >
        <el-form :model="configForm" :rules="configRules" ref="configForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配置名称" prop="configName">
                <el-input v-model="configForm.configName" placeholder="请输入配置名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建人" prop="createdBy">
                <el-input v-model="configForm.createdBy" placeholder="请输入创建人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="配置描述" prop="configDescription">
            <el-input
              type="textarea"
              v-model="configForm.configDescription"
              placeholder="请输入配置描述"
              :rows="3"
            ></el-input>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="目标类" prop="targetClass">
                <el-input v-model="configForm.targetClass" placeholder="请输入目标类全限定名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="方法名" prop="methodName">
                <el-input v-model="configForm.methodName" placeholder="请输入方法名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="方法参数">
            <el-input
              type="textarea"
              v-model="configForm.methodParams"
              placeholder="请输入方法参数(JSON格式)"
              :rows="2"
            ></el-input>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Cron表达式" prop="scheduleCron">
                <el-input v-model="configForm.scheduleCron" placeholder="请输入Cron表达式"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调度类型" prop="scheduleType">
                <el-select v-model="configForm.scheduleType" placeholder="请选择调度类型">
                  <el-option label="固定频率" value="FIXED"></el-option>
                  <el-option label="动态调度" value="DYNAMIC"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="启用定时任务">
                <el-switch v-model="configForm.scheduleEnabled"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行超时(秒)" prop="executeTimeout">
                <el-input-number 
                  v-model="configForm.executeTimeout" 
                  :min="1" 
                  :max="3600" 
                  :step="1"
                  controls-position="right"
                  style="width: 100%;"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="启用重试">
                <el-switch v-model="configForm.retryEnabled"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="最大重试次数" prop="maxRetryCount" v-if="configForm.retryEnabled">
            <el-input-number v-model="configForm.maxRetryCount" :min="0" :max="10"></el-input-number>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer buttons-row">
          <div class="left-actions">
            <el-button @click="dialogVisible = false">取消</el-button>
          </div>
          <div class="right-actions">
            <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { 
  getConfigList, 
  createConfig, 
  updateConfig, 
  deleteConfig, 
  toggleSchedule,
  executeNow 
} from '@/api/assessAlert'

export default {
  name: 'ConfigManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      configList: [],
      selectedConfigs: [],
      searchForm: {
        configName: '',
        enabled: null,
        scheduleEnabled: null
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新建配置',
      isEdit: false,
      configForm: {
        id: null,
        configName: '',
        configDescription: '',
        targetClass: '',
        methodName: '',
        methodParams: '',
        scheduleCron: '',
        scheduleEnabled: false,
        scheduleType: 'FIXED',
        executeTimeout: 300,
        retryEnabled: true,
        maxRetryCount: 3,
        createdBy: ''
      },
      configRules: {
        configName: [
          { required: true, message: '请输入配置名称', trigger: 'blur' }
        ],
        targetClass: [
          { required: true, message: '请输入目标类名', trigger: 'blur' }
        ],
        methodName: [
          { required: true, message: '请输入方法名', trigger: 'blur' }
        ],
        createdBy: [
          { required: true, message: '请输入创建人', trigger: 'blur' }
        ],
        scheduleCron: [
          { required: true, message: '请输入Cron表达式', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadConfigs()
  },
  methods: {
    async loadConfigs() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await getConfigList(params)
        if (response.code === 200) {
          this.configList = response.data.records || response.data
          this.pagination.total = response.data.total || response.data.length
        }
      } catch (error) {
        this.$message.error('加载配置列表失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    searchConfigs() {
      this.pagination.currentPage = 1
      this.loadConfigs()
    },
    resetSearch() {
      this.searchForm = {
        configName: '',
        enabled: null,
        scheduleEnabled: null
      }
      this.pagination.currentPage = 1
      this.loadConfigs()
    },
    refreshData() {
      this.loadConfigs()
    },
    showCreateDialog() {
      this.dialogTitle = '新建配置'
      this.isEdit = false
      this.dialogVisible = true
      this.resetForm()
    },
    editConfig(row) {
      this.dialogTitle = '编辑配置'
      this.isEdit = true
      this.dialogVisible = true
      this.configForm = { ...row }
      this.configForm.scheduleEnabled = row.scheduleEnabled === 1
      this.configForm.retryEnabled = row.retryEnabled === 1
    },
    async submitForm() {
      this.$refs.configForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true
          try {
            const formData = { ...this.configForm }
            formData.scheduleEnabled = formData.scheduleEnabled ? 1 : 0
            formData.retryEnabled = formData.retryEnabled ? 1 : 0

            let response
            if (this.isEdit) {
              response = await updateConfig(formData.id, formData)
            } else {
              response = await createConfig(formData)
            }

            if (response.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.loadConfigs()
            } else {
              this.$message.error(response.msg)
            }
          } catch (error) {
            this.$message.error('操作失败: ' + error.message)
          } finally {
            this.submitting = false
          }
        }
      })
    },
    resetForm() {
      this.configForm = {
        id: null,
        configName: '',
        configDescription: '',
        targetClass: '',
        methodName: '',
        methodParams: '',
        scheduleCron: '',
        scheduleEnabled: false,
        scheduleType: 'FIXED',
        executeTimeout: 300,
        retryEnabled: true,
        maxRetryCount: 3,
        createdBy: ''
      }
      if (this.$refs.configForm) {
        this.$refs.configForm.resetFields()
      }
    },
    async toggleSchedule(row) {
      try {
        const response = await toggleSchedule(row.id, row.scheduleEnabled === 1)
        if (response.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error(response.msg)
          // 恢复原状态
          row.scheduleEnabled = row.scheduleEnabled === 1 ? 0 : 1
        }
      } catch (error) {
        this.$message.error('操作失败: ' + error.message)
        // 恢复原状态
        row.scheduleEnabled = row.scheduleEnabled === 1 ? 0 : 1
      }
    },
    async executeNow(row) {
      try {
        const response = await executeNow(row.id)
        if (response.code === 200) {
          this.$message.success('任务已提交执行')
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('执行失败: ' + error.message)
      }
    },
    async deleteConfig(row) {
      try {
        await this.$confirm('确定要删除这个配置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteConfig(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadConfigs()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    handleSelectionChange(selection) {
      this.selectedConfigs = selection
    },
    async batchToggleSchedule() {
      if (this.selectedConfigs.length === 0) {
        this.$message.warning('请先选择要操作的配置')
        return
      }

      try {
        await this.$confirm('确定要批量切换定时任务状态吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const promises = this.selectedConfigs.map(config => 
          toggleSchedule(config.id, config.scheduleEnabled === 0)
        )
        
        await Promise.all(promises)
        this.$message.success('批量操作成功')
        this.loadConfigs()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量操作失败: ' + error.message)
        }
      }
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadConfigs()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadConfigs()
    },
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    }
  }
}
</script>

<style scoped>
.config-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.operation-bar {
  margin-bottom: 20px;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.config-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.buttons-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.buttons-row .left-actions,
.buttons-row .right-actions {
  display: flex;
  gap: 8px;
}

.action-buttons {
  display: inline-flex;
  gap: 6px;
}
</style>
